/**
 * 
 * @param {String} url 请求地址
 * @param {Object} data 传向接口的数据
 * @param {Function} success表示成功时的回调 
 * @param {Function} error请求失败时的回调 
 */

function getAjax(obj) {
    return new Promise((resolve, reject) => {

        let xhr = new XMLHttpRequest()

        if (obj.data) {
            let str = "?"
            for (let key in obj.data) {
                str += `${key}=${obj.data[key]}`
                str += "&"
            }
            str = str.slice(0, -1)
            obj.url = obj.url + str
            xhr.open("get", obj.url, true)
        } else {
            xhr.open("get", obj.url, true)
        }
        xhr.send()
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(xhr.response)
                } else {
                    reject()
                }

            }
        }
    })
}

/**
 * @param {String} url接口地址
 * @param {Object} data请求传递的参数   
 * @param {Function} success表示成功时的回调
 * @param {Function} error表示失败时的回调
 */
function postAjax(obj) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open("post", obj.url, true)
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded")
        if (obj.data) {
            let str = ''
            for (let key in obj.data) {
                str += `${key}=${obj.data[key]}`
                str += '&'
            }
            str = str.slice(0, -1)
            xhr.send(str)
        } else {
            xhr.send()
        }
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(xhr.response)
                } else {
                    reject()
                }
            }
        }
    })
}